/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
    struct ListNode* partition(ListNode* pHead, int x)
    {
        // write code here
        ListNode* bguard, * gtail, * lguard, * ltail, * cur;
        bguard = gtail = (ListNode*)malloc(sizeof(ListNode));
        lguard = ltail = (ListNode*)malloc(sizeof(ListNode));
        cur = pHead;
        while (cur)
        {
            if (cur->val < x)
            {
                gtail->next = cur;
                gtail = cur;
            }
            else
            {
                ltail->next = cur;
                ltail = cur;
            }
            cur = cur->next;
        }
        ltail->next = NULL;
        gtail->next = lguard->next;
        pHead = bguard->next;
        free(bguard);
        free(lguard);
        return pHead;
    }
};